#include "SnailIOTMonitoringServer.h"

SnailIOTMonitoringServer::SnailIOTMonitoringServer(QObject *parent) : QTcpServer(parent)
{
    qDebug() << "SnailIOTMonitoringServer initialized.";

}

void SnailIOTMonitoringServer::incomingConnection(qintptr socketDescriptor)
{
    qDebug()<<"来了新的";
    // 为新的客户端连接创建一个 QTcpSocket 对象
            QTcpSocket *socket = new QTcpSocket(this);
            if (!socket->setSocketDescriptor(socketDescriptor)) {
                qDebug() << "Failed to set socket descriptor";
                delete socket;
                return;
            }

            // 将新的客户端连接添加到列表中
            clients.append(socket);

            // 连接信号和槽，处理客户端数据
            connect(socket, &QTcpSocket::readyRead, this, [=]() {
                QByteArray data = socket->readAll();
                qDebug() << "Received data from client:" << data;

                // 选择将数据发送给发送该数据的客户端
                sendDataToClient(socket, data);

                // 如果要广播给所有客户端，可以调用 broadcastData 函数
                // broadcastData(data);
            });

            // 处理客户端断开连接的情况
            connect(socket, &QTcpSocket::disconnected, this, [=]() {
                clients.removeOne(socket);
                socket->deleteLater();
                qDebug() << "Client disconnected";
            });

            qDebug() << "New client connected";
}

void SnailIOTMonitoringServer::sendDataToClient(QTcpSocket *client, const QByteArray &data)
{
    if (client && client->state() == QTcpSocket::ConnectedState) {
               client->write(data);
               client->flush();
           }
}

void SnailIOTMonitoringServer::broadcastData(const QByteArray &data)
{
    for (QTcpSocket *client : clients) {
                if (client && client->state() == QTcpSocket::ConnectedState) {
                    client->write(data);
                    client->flush();
                }
            }

}
